package com.itc.dispatch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itc.common.core.utils.OkHttpUtil;
import com.itc.common.core.utils.StringUtils;
import com.itc.dispatch.domain.OaDept;
import com.itc.dispatch.domain.OaUser;
import com.itc.dispatch.domain.vo.OaDeptTreeVo;
import com.itc.dispatch.domain.vo.OaUserTreeVo;
import com.itc.dispatch.service.OaDeptService;
import com.itc.dispatch.mapper.OaDeptMapper;
import com.itc.dispatch.service.OaUserService;
import com.itc.system.api.domain.SysDept;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 91516
* @description 针对表【oa_dept】的数据库操作Service实现
* @createDate 2024-09-24 13:28:43
*/
@Service
public class OaDeptServiceImpl extends ServiceImpl<OaDeptMapper, OaDept>
    implements OaDeptService{

    @Autowired
    private OaUserService oaUserService;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public void oaDeptDataUpdate() {
        //api获取OA部门数据
        Map<String, String> headers = new HashedMap<>();
        headers.put("X-HW-ID", "airport_pfoca_app");
        headers.put("X-HW-APPKEY","Huawei@123!@#");
        Object resultObj = OkHttpUtil.sendOkHttpClient("http://10.81.35.129/api/oaOrg/data"
                , "GET",null,headers);
        if(resultObj == null){
            return;
        }
        JSONObject dataJson = JSONObject.parseObject(resultObj.toString());
        String dataList = dataJson.getString("data");
        if(StringUtils.isBlank(dataList)){
            System.out.println(dataList);
            return;
        }
        try{
            List<OaDept> deptList = objectMapper.readValue(dataList
                    ,new TypeReference<List<OaDept>>(){});
            this.baseMapper.delete(new LambdaQueryWrapper<>());
            this.saveOrUpdateBatch(deptList,500);

        }catch (Exception e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    @Override
    public List<OaDeptTreeVo> getDeptUserTree(OaDept dto) {
        List<OaDeptTreeVo> deptList = this.baseMapper.getDeptTreeList(dto);
        if(deptList.size() == 0){
            return deptList;
        }

        //获取用户信息，并按层级归纳到部门下
        List<OaUserTreeVo> userList = oaUserService.getUserTreeList();
        if(userList.size() > 0){
            Map<String,List<OaUserTreeVo>> userMap = userList.stream().collect(Collectors.groupingBy(OaUserTreeVo::getOrgId));
            for (OaDeptTreeVo oaDept : deptList) {
                if(userMap.get(oaDept.getId()) != null){
                    oaDept.setUserList(userMap.get(oaDept.getId()));
                }
            }
        }

        List<OaDeptTreeVo> resultList = buildDeptTree(deptList);
        return resultList;
    }

    public List<OaDeptTreeVo> buildDeptTree(List<OaDeptTreeVo> depts)
    {
        List<OaDeptTreeVo> returnList = new ArrayList<OaDeptTreeVo>();
        List<String> tempList = depts.stream().map(OaDeptTreeVo::getId).collect(Collectors.toList());
        for (OaDeptTreeVo dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    private void recursionFn(List<OaDeptTreeVo> list, OaDeptTreeVo t)
    {
        // 得到子节点列表
        List<OaDeptTreeVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (OaDeptTreeVo tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private List<OaDeptTreeVo> getChildList(List<OaDeptTreeVo> list, OaDeptTreeVo t)
    {
        List<OaDeptTreeVo> tlist = new ArrayList<OaDeptTreeVo>();
        Iterator<OaDeptTreeVo> it = list.iterator();
        while (it.hasNext())
        {
            OaDeptTreeVo n = (OaDeptTreeVo) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && StringUtils.equals(n.getParentId(),t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<OaDeptTreeVo> list, OaDeptTreeVo t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}




